package com.weixiao.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixiao.dao.UserDao;
import com.weixiao.entity.User;
import com.weixiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2022-12-12 15:48:08
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Cacheable(value = "userList", key = "1")
    @Override
    public List<User> selectUserList(User user) {
        //查出所有符合条件的数据
        List<User> userPOList = baseMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(ObjectUtils.isNotNull(user.getUserId()), User::getUserId, user.getUserId())
                .like(StringUtils.isNotBlank(user.getUserName()), User::getUserName, user.getUserName())
                .eq(StringUtils.isNotBlank(user.getUserSex()), User::getUserSex, user.getUserSex())
                .eq(ObjectUtils.isNotNull(user.getUserAge()), User::getUserAge, user.getUserAge())
                .like(StringUtils.isNotBlank(user.getPassword()), User::getPassword, user.getPassword()));

        return userPOList;
    }

    @Cacheable(value = "userMap", key = "1")
    @Override
    public Map<Integer, User> selectUserMap(User user) {
        //查出所有符合条件的数据
        List<User> userPOList = baseMapper.selectList(new LambdaQueryWrapper<User>()
                .eq(ObjectUtils.isNotNull(user.getUserId()), User::getUserId, user.getUserId())
                .like(StringUtils.isNotBlank(user.getUserName()), User::getUserName, user.getUserName())
                .eq(StringUtils.isNotBlank(user.getUserSex()), User::getUserSex, user.getUserSex())
                .eq(ObjectUtils.isNotNull(user.getUserAge()), User::getUserAge, user.getUserAge())
                .like(StringUtils.isNotBlank(user.getPassword()), User::getPassword, user.getPassword()));
        //将数据转为VO并返回
        Map<Integer, User> userMap = userPOList.stream().collect(Collectors.toMap(User::getUserId, o -> o));
        return userMap;
    }

    /**
     * 修改数据
     *
     * @param user
     */
    //@CacheEvict(value = "userList",key = "1")
    @Override
    public void edit(User user) {
        baseMapper.updateById(user);
        stringRedisTemplate.delete("userList::1");
    }
}

